﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using MultiResolutioning.Data;
using MultiResolutioning.Files;
using MultiResolutioning.Algorithms;
using System.Diagnostics;
using MultiResolutioning.Structures;

namespace MultiResolutionService
{
	/// <summary>
	/// Summary description for Generation
	/// </summary>
	[WebService(Namespace = "http://tempuri.org/")]
	[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
	[System.ComponentModel.ToolboxItem(false)]
	// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
	// [System.Web.Script.Services.ScriptService]
	public class Generation : System.Web.Services.WebService
	{
		private enum Algorithms
		{
			Melax,
			QEM,
			Greedy
		}

		/// <summary>
		/// Generuje siatke wielorozdzielcza.
		/// </summary>
		/// <param name="mesh">Nazwa siatki.</param>
		/// <param name="algorithm">Algorytm.</param>
		/// <param name="iterations">Liczba iteracji.</param>
		/// <returns></returns>
		[WebMethod]
		public string GenerateProgressive(string mesh, string algorithm, int iterations)
		{
			Algorithms algo = (Algorithms)Enum.Parse(typeof(Algorithms), algorithm, true);
			Stopwatch time = new Stopwatch();

			//time.Start();
			ProgressiveMesh progressive = new ProgressiveMesh(PLYMeshFile.LoadFromPLYFile(Context.Server.MapPath("/Meshes/" + mesh + ".ply")));
			
			progressive.mesh.vertices.RemoveAll(x => x.neighbors.Count == 0);

			switch (algo)
			{
				case Algorithms.Melax:
					progressive.simplifier = new MelaxSimplifier();
					break;

				case Algorithms.QEM:
					progressive.simplifier = new QEMSimplifier();
					break;

				case Algorithms.Greedy:
					progressive.simplifier = new GreedySimplifier();
					break;
			}
			time.Start();
			string iterationTime;
			progressive.Simplify(iterations, out iterationTime);
			time.Stop();
			ProgressiveMeshFile.SaveProgressive(progressive, Context.Server.MapPath("/ProgressiveOut/" + algorithm + "/") + mesh);
			//time.Stop();

			return iterationTime;// time.Elapsed.ToString();
		}
	}
}
